/*
 * @(#)TraditionalClient.java    Jul 23, 2010
 *
 * Copyright 2009 Nyber Shanghai, Inc. All rights reserved.
 */

package com.lab.net;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;

/**
 * Class description goes here.
 *
 * @author nickevin@gmail.com
 * @version Jul 23, 2010 9:58:04 AM
 */

public class TraditionalClient {

	public static void main(String[] args) {

		int port = 2000;
		String host = "localhost";
		Socket server = null;

		DataOutputStream os = null;
		FileInputStream is = null;
		int ERROR = 1;

		// connect to server 
		try {
			server = new Socket(host, port);
			System.out.println("Connected with server "
					+ server.getInetAddress() + ":" + server.getPort());
		} catch (Exception e) {
			System.out.println(e);
			System.exit(ERROR);
		}

		try {
			is = new FileInputStream(
					"D:\\Programs\\eclipse-jee-galileo-win32.zip");
			os = new DataOutputStream(server.getOutputStream());

			long start = System.currentTimeMillis();
			long total = send(os, is);
			System.out.println("bytes send--" + total + " and totaltime--"
					+ (System.currentTimeMillis() - start));
		} catch (IOException e) {
			System.out.println(e);
		}

		try {
			os.close();
			server.close();
			is.close();
		} catch (IOException e) {
			System.out.println(e);
		}
	}

	private static long send(DataOutputStream os, FileInputStream is)
			throws IOException {
		byte[] b = new byte[4096];
		long read = 0, total = 0;
		while ((read = is.read(b)) >= 0) {
			total += read;
			os.write(b);
		}

		return total;
	}
}
